import 'package:flutter/material.dart';
import 'package:lib_core/provider/gt_navigator_provider.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lottie/lottie.dart';

/// Loading浮层
class GTLoadingDialog extends StatelessWidget {
  static Map<GTLoadingDialog, BuildContext> dialogMap = {};

  const GTLoadingDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        ///TODO:优化点：点击防抖 点快了在关闭loading后会返回上一个页面
        Navigator.maybePop(context);
      },
      child: UnconstrainedBox(
        child: SizedBox(
          width: 92,
          child: Dialog(
            insetPadding: EdgeInsets.zero,
            child: Container(
              decoration: BoxDecoration(
                // color: GTColors.uikitCmpt12.of(context),
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: GTColors.uikitColorLoadingShadowCard.of(context),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              padding: const EdgeInsets.all(28.0),
              child: SizedBox(
                width: 36,
                child: Lottie.asset(
                  'packages/lib_uikit/assets/json/gt_loading_lottie.json',
                  repeat: true,
                  animate: true,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  static Widget? show({BuildContext? context}) {
    context ??= GTNavigatorProvider.currentContext;
    if (context == null) {
      return null;
    }

    var dialog = const GTLoadingDialog();
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return dialog;
      },
    );

    return dialog;
  }

  static void dismiss({GTLoadingDialog? dialog}) {
    // 获取 context
    BuildContext? context;
    if (dialog != null) {
      context = dialogMap[dialog];
    } else {
      context = GTNavigatorProvider.currentContext;
    }
    if (context == null) {
      return;
    }

    dialogMap.remove(dialog);
    if (!context.mounted) return;
    var navigator = Navigator.of(context);
    if (navigator.canPop()) {
      ///TODO:优化点：点击防抖 点快了在关闭loading后会返回上一个页面
      navigator.pop();
    }
  }
}
